package com.acknight.service.impl;

import com.acknight.constant.SystemConstants;
import com.acknight.dto.Result;
import com.acknight.service.UploadService;
import com.acknight.utils.ConstantPropertiesUtil;
import com.acknight.utils.PathUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.omg.CORBA.SystemException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
public class OssUploadServiceImpl implements UploadService {


    @Override
    public String uploadImg(MultipartFile img) {
        // 判断文件类型
        // 获取原始文件名
        String filename = img.getOriginalFilename();

        if (!filename.endsWith(".png") && !filename.endsWith(".jpg")) {
            throw new RuntimeException(SystemConstants.FILE_TYPE_ERROR);
        }

        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        // 填写Bucket名称
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        /** 创建OSSClient实例。*/
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {

            /** 获取上传文件输入流*/
            InputStream inputStream = img.getInputStream();

            /**获取文件名称*/
            filename = PathUtils.generateFilePath(filename);

            /**调用oss方法实现上传*/
            //第一个参数 Bucket名称
            //第二个参数 上传到oss文件路径或文件名称
            //第三个参数 上传文件输入流
            ossClient.putObject(bucketName, filename, inputStream);

            /** 返回上传到阿里OSS的路径*/
            String url = "https://".concat(bucketName).concat(".").concat(endpoint).concat("/").concat(filename);

            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
